package com.lims;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @author limaosheng
 * @create 2024-04-24 10:11
 * @desc
 */
public class Json判断某个字段是否存在 {
    public static void main(String[] args) {
        String jsonStr = "{\"level1\":{\"level2\":{\"targetField\":1111}}}";
        String targetField = "targetField";

        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String value = getValueFromJson(jsonObject, targetField);

        if (value != null) {
            System.out.println("字段存在，值为: " + value);
        } else {
            System.out.println("字段不存在");
        }
    }

    private static String getValueFromJson(JSONObject jsonObject, String targetField) {
        Object value = jsonObject.get(targetField);
        if (value != null) {
            return value.toString();
        }

        for (String key : jsonObject.keySet()) {
            Object obj = jsonObject.get(key);
            if (obj instanceof JSONObject) {
                String result = getValueFromJson(jsonObject.getJSONObject(key), targetField);
                if (result != null) {
                    return result;
                }
            }else{
                System.out.println("不支持的类型");
            }
        }

        return null;
    }
}
